package uk.ac.bath.legacy;

import java.io.StringWriter;
import java.util.Enumeration;
import java.util.Vector;

import uk.ac.bath.util.MyRandom;

public class MappedOperator implements Cloneable {

    private int[] map_;
    private Operator op_;

    public MappedOperator(Vector map, Operator op) {

        map_ = new int[map.size()];
        int i = 0;
        for (Enumeration e = map.elements(); e.hasMoreElements();) {
            map_[i++] = ((Integer) (e.nextElement())).intValue();
        }

        op_ = op;

    }

    public MappedOperator(int map[], Operator op) {
        int size = map.length;
        map_ = new int[size];
        int i = 0;
        for (; i < size; i++) {
            map_[i] = map[i]; 
        }

        op_ = op;
    }

    public void tick(VectorState in, VectorState out) {
        op_.tick(in, out, map_);
    }

    public int size() {
        return map_.length;
    }


    @Override
    public Object clone() throws CloneNotSupportedException {
        Operator op = (Operator) (op_.clone());
        MappedOperator m = new MappedOperator(map_, op);
        return m;
    }

    public void toString(StringWriter w) {
        op_.toString(w);
        for (int i = 0; i < map_.length; i++) {
            //            w.write(String.valueOf(map_[i]-offset_));
            w.write(String.valueOf(map_[i]));
            if (i != map_.length - 1) {
                w.write(" ");
            }
        }
    }

    static public MappedOperator createRandomMappedOperator(int offset,
            int nOps,
            Operator op) {
        //	Operator op = Operator.createRandomOperator();

        int nArg = op.getStateSize();
        int map[] = new int[nArg];
        map[0] = offset;
        for (int i = 1; i < nArg; i++) {
            int n = MyRandom.nextInt(nOps);
            map[i] = n;
        }

        MappedOperator o = new MappedOperator(map, op);
        return o;
    }
}
